package cn.virens.common.boot.rabbit.autoconfig;

import cn.virens.common.boot.rabbit.RabbitManager;
import cn.virens.common.boot.rabbit.RabbitManagerRegister;
import cn.virens.common.boot.rabbit.RabbitManagerSimple;
import cn.virens.common.boot.rabbit.channel.SimpleChannelListener;
import cn.virens.common.boot.rabbit.mqtt.RabbitMqttService;
import cn.virens.common.boot.rabbit.mqtt.RabbitMqttServiceImpl;
import cn.virens.common.util.exception.APIException;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Role;

@AutoConfiguration
@Role(value = BeanDefinition.ROLE_INFRASTRUCTURE)
@EnableConfigurationProperties({RabbitManageProperties.class})
@ConditionalOnProperty(prefix = "spring.rabbitmq", value = "enabled")
public class RabbitManagAutoConfig {

    @Bean(name = "rabbitManager")
    @DependsOn(value = "rabbitTemplate")
    @ConditionalOnMissingBean(value = RabbitManager.class)
    public RabbitManager rabbitManager(RabbitManageProperties properties, RabbitTemplate template) throws APIException {
        return new RabbitManagerSimple(properties, template);
    }

    @Bean(name = "rabbitMqttService")
    @DependsOn(value = "rabbitTemplate")
    @ConditionalOnMissingBean(value = RabbitMqttService.class)
    public RabbitMqttService rabbitMqttService(RabbitManageProperties properties, RabbitTemplate template) throws APIException {
        return new RabbitMqttServiceImpl(properties, template);
    }

    @DependsOn(value = "amqpAdmin")
    @Bean(value = "rabbitManagerRegister")
    public RabbitManagerRegister rabbitManagerRegister(RabbitManageProperties properties, RabbitAdmin rabbitAdmin) throws APIException {
        return new RabbitManagerRegister(properties, rabbitAdmin);
    }

    @Bean(name = "rabbitChannelListener")
    @DependsOn(value = "rabbitConnectionFactory")
    public SimpleChannelListener rabbitChannelListener(RabbitManageProperties properties, CachingConnectionFactory factory) throws APIException {
        return new SimpleChannelListener(properties, factory);
    }
}
